/**
 * Created by hupeng on 16/6/17.
 */

Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};


function GCell() {
    //事件相关
    var tempDrawLayer = null;//高倒流小区框选结果区域
    var cellLayerFor2G = null;//2G小区图层
    var cellLayer_onMouseOver_handle = null;
    var cellLayer_onMouseOut_handle = null;
    var dialog = null;
    var delta_temp = null; //底图临时数据
    var cell_radius = 0; //小区半径
    var min_flow = 0;
    var query_time = 0;
    var city_list = null;
    var cityId = 0;
    var needShift = false;
    var graphics_temp = null;
    var RqCell = {  //查询小区的条件
        gsm: false,
        td: false,
        lte: false,
        alonecell: 0,
        region: {
            id: 1,
            type: 9000
        }
    };
    var jqGridRowId = 0;
    //初始化数据
    var initData = function () {
        loadCityList();
    };

    /**
     * 加载景区分类
     * */
    var loadCityList = function () {
        $.ajax({
            url: "/getregions?r=" + Math.random(),
            type: "GET",
            async: false,
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    city_list = data;
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };


    //地图改变事件
    var extentchange = function (delta) {
        delta_temp = delta;
        if (!needShift) {
            loadHighFlowCell();
        }
    };

    //加载图例
    var initLegend = function (legends) {
        if (legends == null || legends == undefined || legends.length == 0) {
            gis_common.showMessage("初始化图例失败");
            return;
        }
        var content = "";
        for (var i = 0; i < legends.legendItems.length; i++) {
            var legend = legends.legendItems[i];
            var sRgb = "RGB(" + legend.r + ", " + legend.g + ", " + legend.b + ")"; //sRgb.colorHex()
            content += "<div class=\"legend-box\" style=\"background:rgba(" + legend.r + ", " + legend.g + ", " + legend.b + ",0.5);color:#fff;\"> " + legend.valueMin + "-" + legend.valueMax + "</div>";
        }
        var div = $(content);
        gis_layout.createLegend("endtoend_grid_legend", legends.name + "图例", div);
    };

    /**
     * 高倒流小区
     * */
    this.createHighFlowCell = function (callback) {
        var html = [];
        html.push('<div class="form-horizontal">');
        html.push('    <div class="form-group">');
        html.push('        <label class="col-sm-3 control-label">查询时间:</label>');
        html.push('        <div class="col-sm-9">');
        html.push('            <input id="_e2e_high_flow_time" type="text" class="form-control"');
        html.push('                   onfocus="WdatePicker({lang:\'zh-cn\',dateFmt:\'yyyy-MM\'});"/>');
        html.push('        </div>');
        html.push('    </div>');
        html.push(' <div class="form-group"><label class="col-lg-3 control-label">地市:</label>');
        html.push('    <div class="col-lg-9">');
        html.push('         <select class="form-control _city_list" id="_e2e_high_flow_city"></select>');
        html.push('    </div>');
        html.push(' </div>');
        html.push('    <div class="form-group">');
        html.push('        <label class="col-sm-3 control-label">2G日均流量(MB)(>):</label>');
        html.push('        <div class="col-sm-9">');
        html.push('            <input id="_e2e_high_min_flow" value="300" type="text" class="form-control"/>');
        html.push('        </div>');
        html.push('    </div>');
        html.push('    <div class="form-group">');
        html.push('        <label class="col-sm-3 control-label">无4G覆盖距离(米)(<=):</label>');
        html.push('        <div class="col-sm-9">');
        html.push('            <input id="_e2e_high_flow_range" type="text" class="form-control"/>');
        html.push('        </div>');
        html.push('    </div>');
        html.push('    <div class="form-group">');
        html.push('        <div class="col-sm-9 col-sm-offset-3">');
        html.push('            <button id="_e2e_high_flow_cell_btn" class="btn btn-primary">查 询</button>');
        html.push('        </div>');
        html.push('    </div>');
        html.push('</div>');

        var $div = $(html.join(''));
        $div.find("#_e2e_high_flow_cell_btn").bind("click", function () {
            var $time = $div.find("#_e2e_high_flow_time");
            var highFlowTime = $time.val();
            var $range = $div.find('#_e2e_high_flow_range');
            var range = $range.val();
            var $min = $('#_e2e_high_min_flow');
            var min = $min.val();
            var $city = $('#_e2e_high_flow_city');
            cityId = $city.val();

            if (gis_common.stringIsNullOrWhiteSpace(highFlowTime)) {
                gis_common.showMessage("请输入查询时间");
                $time.focus();
                return;
            }

            if (gis_common.stringIsNullOrWhiteSpace(min)) {
                gis_common.showMessage("请输入最小流量");
                $min.focus();
                return;
            }

            if (gis_common.stringIsNullOrWhiteSpace(range)) {
                gis_common.showMessage("请输入最小间距");
                $range.focus();
                return;
            }

            min_flow = min;
            query_time = highFlowTime;
            cell_radius = range;
            needShift = true;

            loadHighFlowCell();

        });

        var $type = $('._city_list', $div);

        if (city_list) {
            $type.append('<option value="0">所有</option>');
            for (var i = 0, len = city_list.length; i < len; i++) {
                if (city_list[i]['type'] == 9001 && city_list[i]['id'] != 1)
                    $type.append('<option value="' + city_list[i]['id'] + '">' + city_list[i]['name'] + '</option>');
            }
        }

        callback($div);
    };


    var loadHighFlowCell = function () {
        if (cellLayerFor2G) {
            cellLayerFor2G.clear();
        }
        if (query_time == 0 || cell_radius == 0 || min_flow == 0) {
            return;
        }
        var extent = gis_common.getMapExtent();
        if (needShift) {
            extent = {
                "xMin": 104.54519399562771,
                "xMax": 111.37900600437227,
                "yMin": 29.443305712099324,
                "yMax": 32.060712818512634,
                "level": 2,
                "resolution": 0.00475892201166056,
                "wkid": 4326
            };
        }
        gis_common.getMapExtent()
        $.ajax({
            url: "/getadslocmgcell?r=" + Math.random(),
            data: {
                time: query_time.replace('-', ''),
                radius: cell_radius,
                flow: parseInt(min_flow * 1024 * 1024),
                extent: JSON.stringify(extent),
                rqcell: JSON.stringify(RqCell),
                city: cityId
            },
            type: "GET",
            dataType: "json",
            async: true,
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    drawHighFlowCell(data);
                    if (needShift) {
                        drawGCellGridTable();
                    }
                    needShift = false;
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });

    };


    //加载连续弱覆盖数据 表格显示
    var drawGCellGridTable = function () {
        var html = [];
        html.push('<div>');
        html.push("<div><span><button id='_g_cell_export' class='btn btn-primary btn-xs'>导 出</button></span></div>");

        html.push('     <table id="_g_cell_grid_table"></table>');
        html.push('     <div id="_g_cell_grid_pager"></div>');
        html.push('</div>');

        var div = $(html.join(''));

        div.find("#_g_cell_export").click(function () {
            exportGCellResult();
        });

        gis_layout.createLeftWidget("_g_cell_JQGrid_div", "高倒流小区列表", div);

        var time = query_time.replace('-', '');

        div.find("#_g_cell_grid_table").jqGrid({
            url: '/getadslocmgcelllist?time=' + time + '&radius=' + cell_radius + '&flow=' + parseInt(min_flow * 1024 * 1024) + '&city=' + cityId,
            datatype: "json",
            width: 400,
            colNames: ['id', '小区名称', '地市', '上行流量(MB)', '下行流量(MB)', '总流量(MB)', '用户数', '经度', '纬度', 'azimuth', 'antbw'],
            colModel: [{
                name: 'id',
                index: 'id',
                width: 50,
                hidden: true
            }, {
                name: 'gcell_name',
                index: 'gcell_name',
                width: 50
            }, {
                name: 'cityName',
                index: 'cityName',
                width: 40
            }, {
                name: 'up_flow',
                index: 'up_flow',
                width: 40,
                align: "right",
                formatter: function (cellvalue, options, rowObject) {
                    return (cellvalue / (1024 * 1024)).toFixed(5)
                }
            }, {
                name: 'dl_flow',
                index: 'dl_flow',
                width: 40,
                align: "right",
                formatter: function (cellvalue, options, rowObject) {
                    return (cellvalue / (1024 * 1024)).toFixed(5)
                }
            }, {
                name: 'tot_flow',
                index: 'tot_flow',
                width: 40,
                align: "right",
                formatter: function (cellvalue, options, rowObject) {
                    return (cellvalue / (1024 * 1024)).toFixed(5)
                }
            }, {
                name: 'user_cnt',
                index: 'user_cnt',
                width: 40,
                align: "right"
            }, {
                name: 'longitude',
                index: 'longitude',
                width: 50,
                hidden: true
            }, {
                name: 'latitude',
                index: 'latitude',
                width: 50,
                hidden: true
            }, {
                name: 'azimuth',
                index: 'azimuth',
                width: 50,
                hidden: true
            }, {
                name: 'antbw',
                index: 'antbw',
                width: 50,
                hidden: true
            }
            ],
            rowNum: 10,
            rowList: [10, 20, 30, 50],
            pager: '#_g_cell_grid_pager',
            mtype: "get",
            viewrecords: true,
            caption: "",
            onSelectRow: function (id) {
                jqGridRowId = id;
                var data = div.find("#_g_cell_grid_table").jqGrid('getRowData', id);
                //console.log(JSON.stringify(data));
                var xMax = data.longitude * 1 + 0.005;
                var xMin = data.longitude * 1 - 0.005;
                var yMax = data.latitude * 1 + 0.005;
                var yMin = data.latitude * 1 - 0.005;
                gis_common.setExtent(xMax, yMax, xMin, yMin);
                //console.log(JSON.stringify(data));
                createKpiDetailHtmlForGrid(data);
                //drawPolygonGraphic(id);
            }
        });
    };

    //绘制多边形
    var drawPolygonGraphic = function (id) {
        if (graphics_temp) {
            for (var i = 0, len = graphics_temp.length; i < len; i++) {
                if (graphics_temp[i].attributes.data.cell_id == id) {
                    var graphic = graphics_temp[i];
                    drawPointGraphic(graphic);
                    break;
                }
            }
        }
    };

    var exportGCellResult = function () {
        var time = query_time.replace('-', '');
        $.ajax({
            url: "/loadgcellresultcsv",
            data: {
                time: time,
                radius: cell_radius,
                flow: parseInt(min_flow * 1024 * 1024),
                city: cityId
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.isLoadingSunCount();
                gis_common.outPut(req, function (url) {
                    gis_common.windowOpen("pages/export.jsp?typ=application/csv&fid=" + url, "_blank")
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.isLoadingSunCount();
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };


    var createCellCover = function (btses) {
        graphics_temp = [];
        for (var i = 0; i < btses.length; i++) {
            var bts = btses[i];
            if (bts.tag == "cluster") {
                var point = new esri.geometry.Point(bts.longitude, bts.latitude, gis_core.map.spatialReference);

                var symbol = new esri.symbol.PictureMarkerSymbol('/images/cluster.png', 48, 48);
                var graphic = new esri.Graphic(point, symbol);
                cellLayerFor2G.add(graphic);

                var text = bts.value + "";
                if (bts.value >= 1000) {
                    text = (bts.value / 1000).toFixed(2) + "万"
                }
                var textSymbol = new esri.symbol.TextSymbol(text);
                textSymbol.setAlign(esri.symbol.TextSymbol.ALIGN_MIDDLE);
                textSymbol.setColor(new esri.Color([255, 255, 255, 1]));
                textSymbol.setOffset(0, -5);
                var textgraphic = new esri.Graphic(point, textSymbol);
                cellLayerFor2G.add(textgraphic);
            }
            else {
                var antbw = 30;
                var azimuth = 0;
                var off_azimuth = 0;
                if (bts.cells.length > 1) {
                    antbw = 180.0 / bts.cells.length;
                    off_azimuth = 360.0 / bts.cells.length;
                }
                if (antbw > 30) {
                    antbw = 30;
                }

                for (var j = 0; j < bts.cells.length; j++) {
                    var cell = bts.cells[j];
                    cell.radius = 50;
                    cell.antbw = antbw;
                    if (cell.azimuth == 0) {
                        cell.azimuth = azimuth;
                    }
                    var g = gis_common.createCellGraphic(cell);
                    var flow = cell.tot_flow;
                    var symbol = new esri.symbol.SimpleFillSymbol();
                    if (flow >= (min_flow * 1024 * 1024)) {
                        symbol.setColor(new esri.Color([255, 40, 75, 1]));
                        symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 40, 75, 0.8]), 1));
                    } else {
                        symbol.setColor(new esri.Color([151, 151, 151, 1]));
                        symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([151, 151, 151, 0.8]), 1));
                    }
                    g.setSymbol(symbol);
                    cellLayerFor2G.add(g);
                    graphics_temp.push(g);
                    azimuth = azimuth + off_azimuth;
                }
            }
        }
    };

    /**
     * 绘制高导流小区
     * */
    var drawHighFlowCell = function (data) {

        createCellCover(data);

        if (jqGridRowId != 0) {
            drawPolygonGraphic(jqGridRowId);
        }

        if (needShift && data && data.length > 0) {
            var xMin = data[0].longitude;
            var xMax = data[0].longitude;
            var yMin = data[0].latitude;
            var yMax = data[0].latitude;
            for (i = 0, len = data.length; i < len; i++) {
                if (data[i].longitude > xMax) {
                    xMax = data[i].longitude;
                }
                if (data[i].longitude < xMin) {
                    xMin = data[i].longitude;
                }
                if (data[i].latitude > yMax) {
                    yMax = data[i].latitude;
                }
                if (data[i].latitude < yMin) {
                    yMin = data[i].latitude;
                }
            }


            if (xMax && yMax && xMin && yMin) {
                gis_common.setExtent(xMax, yMax, xMin, yMin);
            }
        }
    };


    var capitalClick = function (event) {
        var cell = event.graphic.attributes.data;
        console.log(JSON.stringify(cell));
        createKpiDetailHtml(cell);
        drawPointGraphic(event.graphic);
    };


    //绘制多边形
    var drawPointGraphic = function (graphic) {
        if (tempDrawLayer) {
            tempDrawLayer.clear()
        }

        if (!graphic && !graphic.geometry && !graphic.geometry.rings) {
            return;
        }

        var rings = graphic.geometry.rings[0];
        var l = parseInt(rings.length / 2);
        var xy0 = rings[0];
        var xy1 = rings[l];
        var x = (xy0[0] + xy1[0]) / 2;
        var y = (xy0[1] + xy1[1]) / 2;
        var point = new esri.geometry.Point(x, y, gis_core.map.spatialReference);
        var symbol = new esri.symbol.PictureMarkerSymbol('/images/point-green.png', 26, 26);
        var graphic1 = new esri.Graphic(point, symbol, rings, null);
        tempDrawLayer.add(graphic1);
    };

    var createKpiDetailHtmlForGrid = function (data) {
        var kpi = [];

        if (data) {

            if (data.gcell_name) {
                kpi.push({"id": "小区名称", "name": data.gcell_name});
            }
            if (data.up_flow) {
                kpi.push({"id": "上行流量(MB)", "name": data.up_flow});
            }
            if (data.dl_flow) {
                kpi.push({"id": "下行流量(MB)", "name": data.dl_flow});
            }
            if (data.tot_flow) {
                kpi.push({"id": "总流量(MB)", "name": data.tot_flow});
            }
            if (data.user_cnt) {
                kpi.push({"id": "用户数", "name": data.user_cnt});
            }

        }
        var div = gis_common.createKeyValueList(kpi);
        gis_layout.createRightWidget("_2g_gcell_kpi", "KPI", div);
    };

    /**
     * 创建指标明细html
     * */
    var createKpiDetailHtml = function (data) {
        var kpi = [];

        if (data) {

            if (data.gcell_name) {
                kpi.push({"id": "小区名称", "name": data.gcell_name});
            }
            if (data.up_flow) {
                kpi.push({"id": "上行流量(MB)", "name": (data.up_flow / (1024 * 1024)).toFixed(5)});
            }
            if (data.dl_flow) {
                kpi.push({"id": "下行流量(MB)", "name": (data.dl_flow / (1024 * 1024)).toFixed(5)});
            }
            if (data.tot_flow) {
                kpi.push({"id": "总流量(MB)", "name": (data.tot_flow / (1024 * 1024)).toFixed(5)});
            }
            if (data.user_cnt) {
                kpi.push({"id": "用户数", "name": data.user_cnt});
            }

        }
        var div = gis_common.createKeyValueList(kpi);
        gis_layout.createRightWidget("_2g_gcell_kpi", "KPI", div);
    };


    var query = function (keywords, callback) {

        if (query_time == 0 || cell_radius == 0 || min_flow == 0) {
            return;
        }

        var time = query_time.replace('-', '');

        $.ajax({
            url: "/getgcelltopn",
            data: {
                time: time,
                radius: cell_radius,
                flow: parseInt(min_flow * 1024 * 1024),
                city: cityId,
                key: keywords,
                topn: 10

            },
            dataType: "json",
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                var resvalues = eval(req);
                callback(resvalues);
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError("小区模糊查询出错：" + XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    /**
     * 初始化
     */
    this.init = function () {
        //加载库文件
        dojo.require("esri.layers.WMSLayerInfo");
        dojo.require("esri.layers.WMSLayer");
        dojo.require("esri.toolbars.draw");
        tempDrawLayer = gis_core.addGraphicsLayerWithIndex('temp_draw_layer', '高亮选中小区', 3);
        cellLayerFor2G = gis_core.addGraphicsLayerWithIndex('cell_layer_for_2g', '区域框选', 2);
        dojo.connect(cellLayerFor2G, "onClick", capitalClick);
        gis_core.addExtentChange("GCell", extentchange);
        /*
         if (cellLayer_onMouseOver_handle != null) {
         dojo.disconnect(cellLayer_onMouseOver_handle);
         }
         cellLayer_onMouseOver_handle = cellLayer.on("mouse-over", tooltip);

         if (cellLayer_onMouseOut_handle != null) {
         dojo.disconnect(cellLayer_onMouseOut_handle);
         }
         cellLayer_onMouseOut_handle = cellLayer.on("mouse-out", closeDialog);*/

        //注册查询事件
        gis_common.queryRegisterFun("gcell", query);

        //注册模块
        gis_core.addPlugin(this);
        gis_core.pluginDestroyExceptId(this.title.id);
        initData();
    };

    /**
     * 销毁
     */
    this.destroy = function () {
        gis_core.removeExtentChange("GCell");
        gis_layout.removeRightWidget("_2g_gcell_kpi");
        gis_layout.removeLeftWidget("_g_cell_JQGrid_div");
        if (tempDrawLayer) {
            tempDrawLayer.clear();
        }
        if (cellLayerFor2G) {
            cellLayerFor2G.clear();
        }

        needShift = false;
        jqGridRowId = 0;
    };

    /**
     * 模块信息
     * @type {{id: string, name: string}}
     */
    this.title = {
        id: "01_03_00",
        name: "2G高倒流小区"
    };
}

//功能类 全局类
var gCell = null;

function initGCell() {
    if (gCell == null) {
        gCell = new GCell();
    }
    gCell.init();
}

function gCell_Init() {
    initGCell();

}


//高倒流小区
function endToEnd_createHighFlowCellHtml(obj) {
    initGCell();
    gis_core.pluginDestroyExceptId(gCell.title.id);
    gis_layout.createMenubarWithFun("endtoend_createHighFlowCell", obj, '2G高倒流小区', gCell.createHighFlowCell);
}